<template>
  <div class="blog-comment-container">
    <MessageArea
        :isListLoading="loading"
        :list="data.rows"
        :subTitle="`(${data.total})`"
        title="评论列表"
    />
  </div>
</template>
<script lang="ts" setup>
import { getComments, postComment } from '@/api/blog'
import MessageArea from '@/components/MessageArea/index.vue'
import { useFetchData } from '@/hooks/useFetchData'
import emitter from '@/utils/EventBus'
import { useRoute } from 'vue-router'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'

const route: any = useRoute()

const page = ref(1)
const limit = ref(10)


const fetchData = () => {
  return getComments({ blogid: route.params.id, page: page.value, limit: limit.value }).then(
      (res) => res.data
  )
}

const { data, loading } = useFetchData<{ total: number; rows: any[] }>({
  defaultValue: { total: 0, rows: [] },
  fetchData
})

const hasMore = computed(() => data.value.total > page.value * limit.value)

// 加载更多
const fetchMore = async () => {
  if (!hasMore.value) return
  loading.value = true
  page.value++
  const res = await fetchData()
  loading.value = false
  data.value.rows = [...data.value.rows, ...res.rows]
}

const handleScroll = (dom: HTMLDivElement) => {
  if (loading.value || !dom) return
  const range = 100
  const dis = dom.scrollHeight - (dom.clientHeight + dom.scrollTop)
  if (dis <= range) {
    fetchMore()
  }
}

onMounted(() => {
  emitter.on('mainScroll', handleScroll)
})

onBeforeUnmount(() => {
  emitter.off('mainScroll', handleScroll)
})

emitter.on('submit', async (formData: any, callback: (msg: string) => void) => {
  const resp = await postComment({
    blogId: route.params.id,
    ...formData
  }).then((res) => res.data)
  data.value.rows.unshift(resp)
  data.value.total++
  callback('评论成功') // 告诉子组件，我这边处理完了，你继续
})
</script>
<style lang="less" scoped>
.blog-comment-container {
  margin: 30px 0;
}
</style>